#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
股票预测应用启动脚本
"""
import sys
import os
import subprocess
import logging

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'pandas', 'numpy', 'yfinance', 'akshare', 'matplotlib', 
        'seaborn', 'scikit-learn', 'requests', 'beautifulsoup4',
        'streamlit', 'plotly', 'ta'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            logger.info(f"✅ {package} 已安装")
        except ImportError:
            missing_packages.append(package)
            logger.warning(f"❌ {package} 未安装")
    
    if missing_packages:
        logger.error(f"缺少依赖包: {missing_packages}")
        logger.info("正在安装缺少的包...")
        
        for package in missing_packages:
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install", package])
                logger.info(f"✅ {package} 安装成功")
            except subprocess.CalledProcessError:
                logger.error(f"❌ {package} 安装失败")
                return False
    
    return True

def test_modules():
    """测试模块导入"""
    try:
        from data_fetcher import get_data_fetcher
        from stock_screener import StockScreener
        from technical_analysis import TechnicalAnalyzer
        from prediction_model import StockPredictor
        
        logger.info("✅ 所有自定义模块导入成功")
        
        # 简单功能测试
        logger.info("正在测试数据获取...")
        fetcher = get_data_fetcher()
        
        # 测试基本功能
        logger.info("✅ 模块测试通过")
        return True
        
    except Exception as e:
        logger.error(f"❌ 模块测试失败: {e}")
        return False

def launch_app():
    """启动Streamlit应用"""
    try:
        logger.info("🚀 启动股票预测应用...")
        
        # 启动Streamlit应用
        cmd = [sys.executable, "-m", "streamlit", "run", "main_app.py", "--server.port=8501"]
        subprocess.run(cmd)
        
    except KeyboardInterrupt:
        logger.info("👋 应用已停止")
    except Exception as e:
        logger.error(f"❌ 应用启动失败: {e}")

def main():
    """主函数"""
    print("=" * 60)
    print("🎯 A股中长期投资分析系统")
    print("=" * 60)
    
    # 检查依赖
    print("\n📦 检查依赖包...")
    if not check_dependencies():
        print("❌ 依赖检查失败，请手动安装缺少的包")
        return
    
    # 测试模块
    print("\n🧪 测试模块...")
    if not test_modules():
        print("❌ 模块测试失败")
        return
    
    print("\n✅ 系统检查完成，准备启动应用...")
    print("\n📝 使用说明:")
    print("1. 应用将在浏览器中打开 (http://localhost:8501)")
    print("2. 首次运行可能需要较长时间获取数据")
    print("3. 请确保网络连接正常")
    print("4. 按 Ctrl+C 可停止应用")
    
    input("\n按回车键启动应用...")
    
    # 启动应用
    launch_app()

if __name__ == "__main__":
    main()
